﻿using System.Threading;
using System.Threading.Tasks;
using GreenPipes;
using MassTransit;
using MassTransit.Courier.Factories;
using Microsoft.Extensions.Hosting;
using MassTransitDemo.ProcessingService.Activities;
using MassTransitDemo.ProcessingService.Models;

namespace MassTransitDemo.ProcessingService
{
    public class ResponseHostedService : IHostedService
    {
        IBusControl _busControl;

        public async Task StartAsync(CancellationToken stoppingToken)
        {
            var rabbitMQAddress = "119.3.138.127";
            var validateQueueName = "execute_validate";
            var retrieveQueueName = "execute_retrieve";
            var retrieveCompensateQueueName = "compensate_retrieve";

            _busControl = Bus.Factory.CreateUsingRabbitMq(x =>
            {
                x.Host(rabbitMQAddress, 5672, "masstransitdemo", h =>
                {
                    h.Username("masstransitdemo");
                    h.Password("masstransitdemo@test");
                });

                x.ReceiveEndpoint(validateQueueName, e =>
                {
                    e.PrefetchCount = 100;
                    e.ExecuteActivityHost(DefaultConstructorExecuteActivityFactory<ValidateActivity, IValidateArguments>.ExecuteFactory, c => c.UseRetry(r => r.Immediate(5)));
                });

                x.ReceiveEndpoint(retrieveQueueName, e =>
                {
                    e.PrefetchCount = 100;
                    e.ExecuteActivityHost<RetrieveActivity, IRetrieveArguments>(c => c.UseRetry(r => r.Immediate(5)));
                });

                x.ReceiveEndpoint(retrieveCompensateQueueName, e =>
                {
                    e.CompensateActivityHost<RetrieveActivity, IRetrieveLog>(c => c.UseRetry(r => r.Immediate(5)));
                });
            });

            await _busControl.StartAsync();
        }

        public Task StopAsync(CancellationToken stoppingToken)
        {
            _busControl?.Stop();
            return Task.CompletedTask;
        }
    }
}
